package com.zimmur.quartz;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zimmur.common.JPushCommon;
import com.zimmur.common.PropertiesCommon;
import com.zimmur.model.account.User;
import com.zimmur.model.account.UserMessage;
import com.zimmur.service.IUserService;
import com.zimmur.service.account.IUserMessageService;

@Component
public class ProcessPushMessage {
	private static Logger log=LoggerFactory.getLogger(ProcessPushMessage.class);
	@Resource
	private IUserMessageService userMessageService;
	@Resource
	private IUserService userService;
	@Value("${JPUSH.MasterSecret}")
	private String pushMasterSecret;
	@Value("${JPUSH.AppKey}")
	private String pushAppkey;
	//是否生产环境
	@Value("${JPUSH.Production}")
	private boolean isProduction=false;
	
	/**
     * 每隔两分钟执行一次
     * @Scheduled(fixedRate = 2*60*1000) 
     */
//	@Scheduled(fixedRate=2*60*1000)
	public void handleUserPushMessage(){
		
		List<UserMessage> userMessagesList = userMessageService.selectNonePushList();
		if(!userMessagesList.isEmpty()){
			User user=null;
			List<UserMessage> pushList = new ArrayList<>();
			String jsonObj=null;
			
			try {
				for (UserMessage userMessage : userMessagesList) {
					pushList.add(userMessage);
					Long userId=userMessage.getToUserId();
					if(userId!=null){
						user = userService.getUserInfoByUserId(userId);
					}
					if(!userMessage.getMsgTitle().equals("") && user != null && !user.getDeviceId().equals("")){
						//推送的通知，暂时没用到jsonObj
						//jsonObj = JSON.toJSONString(userMessage);					
						JPushCommon.Instance(pushMasterSecret, pushAppkey,isProduction).SendNotifyMessage(userMessage.getMsgTitle(), 
							user.getDeviceId(), jsonObj);
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
			
			try {
				if(pushList.size()>0){
					userMessageService.updateMessagePushStatusByIds(pushList);
				}
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
		}
		log.info("call handleUserPushMessage");
	}
	
	
}
